package com.snpic.appaw.module.third.service.httpclient;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.snpic.appaw.module.third.dal.dataobject.common.ThirdPartyFlowRecord;
import com.snpic.appaw.module.third.service.common.ThirdPartyFlowRecordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.util.Map;

@Slf4j
@Service
public class HttpClientServerImpl implements HttpClientServer{
	@Resource
	private ThirdPartyFlowRecordService thirdPartyFlowRecordService;

	// 客户端配置（单例模式）
	private static final CloseableHttpClient httpClient;

	static {
		RequestConfig config = RequestConfig.custom()
			.setConnectTimeout(10000)  // 连接超时10秒（单位：毫秒）
			.setSocketTimeout(30000)  // 数据传输超时30秒
			.build();

		httpClient = HttpClients.custom()
			.setDefaultRequestConfig(config)
			.build();
	}

	/**
	 * 发送GET请求
	 *
	 * @param url     请求地址
	 * @param headers 请求头
	 * @return 响应内容
	 */
	public static String doGet(String url, Map<String, String> headers) {
		return "";
	}

	/**
	 * 发送POST请求（JSON格式）
	 *
	 * @param url      请求地址
	 * @param jsonBody JSON请求体
	 * @param headers  请求头
	 * @return 响应内容
	 */
	@Override
	public String doPostJson(String url, String jsonBody, Map<String, String> headers,String ThirdPartyName,String TypeName) throws HttpClientException {
		HttpPost httpPost = new HttpPost(url);
		setHeaders(httpPost, headers);
		httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));
//		httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
		httpPost.setHeader("Content-Type", "application/json");

		//第三方接口请求，流水记录到数据表
		ThirdPartyFlowRecord record = new ThirdPartyFlowRecord();
		record.setTypeName(TypeName);
		record.setThirdParty(ThirdPartyName);
		record.setRequestPath(url);
		record.setRequestMessage(jsonBody);
		Long recordId = thirdPartyFlowRecordService.record(record);

		try {
			HttpResponse response = httpClient.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();

			// 状态码判断
			if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() >= 501) {
					log.error("POST请求失败，状态码：{}，URL：{}", statusLine.getStatusCode(), url);
					throw new HttpClientException("HTTP状态码异常: " + statusLine.getStatusCode());
			}
			String executeStr = EntityUtils.toString(response.getEntity(), "UTF-8");

			// 第三方接口请求,更新记录响应
			if(StrUtil.isNotBlank(executeStr)){
				record.setResponseMessage(executeStr);
				thirdPartyFlowRecordService.update(record);
			}

			return executeStr;
		} catch (Exception e) {
			throw new HttpClientException("POST请求异常: " + e.getMessage(), e);
		}
	}

	/**
	 * 发送POST请求（JSON格式）- 支持对象自动转换
	 *
	 * @param url     请求地址
	 * @param bodyObj 请求体对象（自动转换为JSON）
	 * @param headers 请求头
	 * @param ThirdPartyName 第三方名称
	 * @param TypeName    接口类型名称
	 * @return 响应内容
	 */
	@Override
	public String doPostJson(String url, Object bodyObj, Map<String, String> headers,String ThirdPartyName,String TypeName) throws HttpClientException {
		return doPostJson(url, JSONUtil.toJsonStr(bodyObj), headers,ThirdPartyName,TypeName);
	}


	private static void setHeaders(HttpUriRequest request, Map<String, String> headers) {
		if (headers != null) {
			headers.forEach(request::setHeader);
		}
	}

	// 自定义异常
	public static class HttpClientException extends RuntimeException {
		public HttpClientException(String message) {
			super(message);
		}

		public HttpClientException(String message, Throwable cause) {
			super(message, cause);
		}
	}
}
